package com.itheima.prize.msg;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.prize.commons.config.RedisKeys;
import com.itheima.prize.commons.db.entity.*;
import com.itheima.prize.commons.db.mapper.CardGameMapper;
import com.itheima.prize.commons.db.mapper.CardGameProductMapper;
import com.itheima.prize.commons.db.service.*;
import com.itheima.prize.commons.utils.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 活动信息预热，每隔1分钟执行一次
 * 查找未来1分钟内（含），要开始的活动
 */
@Component
public class GameTask {
    private final static Logger log = LoggerFactory.getLogger(GameTask.class);
    @Autowired
    private CardGameService gameService;
    @Autowired
    private CardGameProductService gameProductService;
    @Autowired
    private CardGameRulesService gameRulesService;
    @Autowired
    private GameLoadService gameLoadService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CardProductService cardProductService;
    @Autowired
    private RedisTemplate redisTemplate;
@Autowired
private CardGameMapper cardGameMapper;
@Autowired
private CardGameProductMapper cardGameProductMapper;
    @Scheduled(cron = "0 0/1 * * * ?   ")
    public Map<String,Object> execute() {

        System.out.printf("scheduled!"+new Date());
        Random rand = new Random();
        RedisUtil redisUtil1=new RedisUtil();
        //查询1分钟内开始的活动
        LambdaQueryWrapper<CardGame> wrapper=new LambdaQueryWrapper<>();
        Map<String,Object> map=new HashMap<>();
        Map<String,Integer> mapGoal=new HashMap<>();
        Map<String,Integer> mapEnter=new HashMap<>();
        Map<Long,CardProductDto> mapProduct=new HashMap<>();
        Date date=new Date();
        long time = date.getTime()+100000*60;
        Date newdate=new Date(time);
        wrapper.lt(CardGame::getStarttime,newdate);
        wrapper.gt(CardGame::getStarttime,new Date());
        List<CardGame> cardGames = cardGameMapper.selectList(wrapper);
        //如果当前分钟为null
        if (!CollectionUtils.isNotEmpty(cardGames)){
            Map<String,Object> map1=new HashMap<>();
            return map1;
        }

        cardGames.forEach(cardGame -> {
            //记录活动信息
            redisTemplate.opsForValue().set(RedisKeys.INFO+cardGame.getId(),cardGame);
            cardGame.setStatus(1);
            gameService.updateById(cardGame);
            long endTime=cardGame.getEndtime().getTime();
            long starTime=cardGame.getStarttime().getTime();
            LambdaQueryWrapper<CardGameProduct> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(CardGameProduct::getGameid,cardGame.getId());
            List<CardGameProduct> list1 = gameProductService.list(wrapper1);
//            记录商品信息
            list1.forEach(li->{
                //获得商品的id以及
                LambdaQueryWrapper<CardProduct> wrapper3=new LambdaQueryWrapper<>();
                wrapper3.eq(CardProduct::getId,li.getProductid());
                List<CardProduct> list = cardProductService.list(wrapper3);

                list.forEach(l->{
                    CardProductDto cardProductDto=new CardProductDto();
                    LambdaQueryWrapper<CardGameProduct> wrapper4=new LambdaQueryWrapper<>();
                    wrapper4.eq(CardGameProduct::getProductid,l.getId());
                    wrapper4.eq(CardGameProduct::getGameid,cardGame.getId());
                    CardGameProduct cardGameProduct =gameProductService.selectone(wrapper4);
                    cardProductDto.setAmount(cardGameProduct.getAmount());
                    BeanUtils.copyProperties(l,cardProductDto);
                    //解决令牌重复问题
                    long duration=endTime-starTime;
                    int duration1=(int)duration;
                    if(duration1<0){
                        duration1=-duration1;
                    }
                    long time1 = starTime+rand.nextInt(duration1);
                    time1=time1*1000+rand.nextInt(999);
                    mapProduct.put(time1,cardProductDto);

                });
            });


            //记录最大中奖励次数记录参与次数
            LambdaQueryWrapper<CardGameRules> wrapperRules=new LambdaQueryWrapper<>();
            wrapperRules.eq(CardGameRules::getGameid,cardGame.getId());
            List<CardGameRules> list = gameRulesService.list(wrapperRules);
            list.forEach(cardGameRules -> {
                mapGoal.put(String.valueOf(cardGameRules.getUserlevel()),cardGameRules.getGoalTimes());
                mapEnter.put(String.valueOf(cardGameRules.getUserlevel()),cardGameRules.getEnterTimes());
            });

            redisTemplate.opsForValue().set(RedisKeys.MAXGOAL+cardGame.getId(),mapGoal);
            redisTemplate.opsForValue().set(RedisKeys.MAXENTER+cardGame.getId(),mapEnter);
            redisTemplate.opsForValue().set(RedisKeys.TOKEN+cardGame.getId(),mapProduct);
            map.put(RedisKeys.INFO+cardGame.getId(),cardGame);
            map.put(RedisKeys.MAXGOAL+cardGame.getId(),mapGoal);
            map.put(RedisKeys.MAXENTER+cardGame.getId(),mapEnter);
            map.put(RedisKeys.TOKEN+cardGame.getId(),mapProduct);
        });

        return map;
    }
}
